package com.fyzk.utils;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DesUtil {
	
	
	private static final String key = "lotterytest";
	
//	protected static final Logger logger=LoggerFactory.getLogger(DesUtil.class);

	private final static String DES = "DES";
	
	/**
	 * 加密
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String data) {
		byte[] bt;
		String strs = "";
		try {
			bt = encrypt(data.getBytes(), key.getBytes());
			strs = Base64.encode(bt);
		} catch (Exception e) {
			L.e("des加密失败",e.getMessage());
			e.printStackTrace();
		}
		return strs;
	}

    /**
     * 解密
     * @param data
     * @return
     * @throws IOException
     * @throws Exception
     */
	public static String decrypt(String data) {
		if (data == null)
			return null;
		byte[] buf = null,bt = null;
		try {
			buf = Base64.decode(data);
			bt = decrypt(buf, key.getBytes());
		} catch (IOException e) {
			L.e("des解密失败",e.getMessage());
			e.printStackTrace();
		}catch (Exception e) {
			L.e("des解密失败",e.getMessage());
			e.printStackTrace();
		}
		return new String(bt);

	}
	/**
	 * 根据键值进行加密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
		return cipher.doFinal(data);
	}
	/**
	 * 根据键值进行解密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
		return cipher.doFinal(data);
	}

}